<template>
	<view class="container">
		<view class="page-body">
			<view class='wrapper'>
				<view class='toolbar' @tap="format">
					<view :class="formats.bold ? 'ql-active' : ''" class="iconfont icon-zitijiacu" data-name="bold"></view>
					<view :class="formats.align === 'left' ? 'ql-active' : ''" class="iconfont icon-zuoduiqi" data-name="align"
					 data-value="left"></view>
					<view :class="formats.align === 'center' ? 'ql-active' : ''" class="iconfont icon-juzhongduiqi" data-name="align"
					 data-value="center"></view>
					<view :class="formats.align === 'right' ? 'ql-active' : ''" class="iconfont icon-youduiqi" data-name="align"
					 data-value="right"></view>
					<view :class="formats.backgroundColor === '#00ff00' ? 'ql-active' : ''" class="iconfont icon-fontbgcolor"
					 data-name="backgroundColor" data-value="#00ff00"></view>
					<view class="iconfont icon--checklist" data-name="list" data-value="check"></view>
					<view :class="formats.list === 'ordered' ? 'ql-active' : ''" class="iconfont icon-youxupailie" data-name="list"
					 data-value="ordered"></view>
					<view :class="formats.list === 'bullet' ? 'ql-active' : ''" class="iconfont icon-wuxupailie" data-name="list"
					 data-value="bullet"></view>
					<view class="iconfont icon-outdent" data-name="indent" data-value="-1"></view>
					<view class="iconfont icon-indent" data-name="indent" data-value="+1"></view>
					<view class="iconfont icon-fengexian" @tap="insertDivider"></view>
					<view :class="formats.header === 1 ? 'ql-active' : ''" class="iconfont icon-format-header-1" data-name="header"
						:data-value="1"></view>
					<view :class="formats.header === 2 ? 'ql-active' : ''" class="iconfont icon-format-header-2" data-name="header"
						:data-value="2"></view>
					<view :class="formats.header === 3 ? 'ql-active' : ''" class="iconfont icon-format-header-3" data-name="header"
						:data-value="3"></view>
				</view>
				
				<view style="margin: 20rpx 0 30rpx 30rpx;">
					<u--input
						:disabled="editButtonShow"
						disabledColor="#fff"
					    placeholder="笔记标题"
						placeholderStyle="fontSize:50rpx"
					    border="none"
						fontSize="40rpx"
					    v-model="info.title">
					</u--input>
				</view>
				
				<u-divider></u-divider>

				<editor @input="editText" id="editor" class="ql-container" :placeholder="placeholder" showImgSize showImgToolbar showImgResize
				 @statuschange="onStatusChange" :read-only="readOnly" @ready="onEditorReady">
				</editor>
			</view>
		</view>

		<view class="save-button" v-show="saveButtonShow" @click="updateNote"></view>
		<view class="edit-button" v-show="editButtonShow" @click="editButtonShow = false;readOnly = false;"></view>
	</view>
</template>

<script>
	import { add,update,getInfo } from '@/api/note'
	export default {
		props:{
			value:{
				type:String,
				default:''
			},
			placeholder:{
				type:String,
				default:'开始输入...'
			}
		},
		data() {
			return {
					editButtonShow:false,
					saveButtonShow:false,
					isConfirm:false, //处理返回逻辑
					info:{
						id:'',
						title:'无笔记标题',
						content:'',
					},
					readOnly: false,
					formats: {}
				}
		},
		onLoad(option) {
			uni.loadFontFace({
				family: 'Pacifico',
				source: 'url("./Pacifico.ttf")'
			})
			if(option.id){
				// 查询笔记
				this.readOnly = true
				this.editButtonShow = true
				this.getNote(option.id)
			}else{
				// 创建笔记
				this.addNote()
			}
			// 监听返回事件，只支持微信小程序
			//#ifdef MP-WEIXIN
			wx.enableAlertBeforeUnload({
				message: "您的笔记是否已保存，确认退出吗？",
				success: function (res) {
					
				},
				fail: function (err) {
					
				},
			});
			//#endif
		},
		// 实例销毁之前调用
		beforeDestroy() {
			//#ifdef MP-WEIXIN
			// 取消监听
			wx.disableAlertBeforeUnload();
			//#endif
		},
		onBackPress() {
			if(this.isConfirm == false&&this.saveButtonShow){
				uni.showModal({
					title: "是否保存？",
					content: "是否保存本次修改",
					confirmText: '是',
					cancelText: '否',
					success:  res => {
						if (res.confirm){
							this.isConfirm = true
							this.updateNote()
							uni.navigateBack()
						}else{
							this.isConfirm = true
							uni.navigateBack()
						}
					}
				})
				return true
			}else{
				return false
			}
		},
		methods: {
			async getNote(id){
				const { data } = await getInfo(id)
				if (data.code == 200) {
					this.info = data.data
				}else{
					uni.showToast({ title: data.msg, icon: 'none' })
					return
				}
			},
			async updateNote(){
				try {
				    const { data } = await update(this.info)
				    if (data.code == 200) {
						this.saveButtonShow = false
				    }else{
						uni.showToast({ title: data.msg, icon: 'none' })
						return
					}
				} catch (error) {
					uni.showToast({ title: '笔记保存失败', icon: 'none' })
				    return
				}
			},
			async addNote(){
				try {
					this.info.title = '无笔记标题'
				    const { data } = await add(this.info)
				    if (data.code == 200) {
						this.info = data.data
				    }else{
						uni.showToast({ title: data.msg, icon: 'none' })
						return
					}
				} catch (error) {
					uni.showToast({ title: '笔记创建失败', icon: 'none' })
				    return
				}
			},
			
			editText(res){
				this.saveButtonShow = true
				this.$emit('editorChange',res.detail.html)
				this.info.content = res.detail.html
			},
			readOnlyChange() {
				this.readOnly = !this.readOnly
			},
			onEditorReady() {
				setTimeout(() => {
					uni.createSelectorQuery().select('#editor').context((res) => {
						this.editorCtx = res.context
						this.editorCtx.setContents({    
							// html:this.value    //初始化赋值内容
							html:this.info.content
						})    
					}).exec()
				}, 600)
			},
			format(e) {
				let {
					name,
					value
				} = e.target.dataset
				if (!name) return
				// console.log('format', name, value)
				this.editorCtx.format(name, value)
			},
			onStatusChange(e) {
				const formats = e.detail
				this.formats = formats
			},
			insertDivider() {
				this.editorCtx.insertDivider({
					success: function() {
						console.log('insert divider success')
					}
				})
			},
		},
	}
</script>

<style> 
	@import "./cs.css";
	.wrapper {
		padding: 5px;
	}
	.toolbar{
		/* border: 1upx #000 solid; */
	}
	.iconfont {
		display: inline-block;
		padding: 8px 8px;
		width: 24px;
		height: 24px;
		cursor: pointer;
		font-size: 20px;
	}
	.toolbar {
		box-sizing: border-box;
		border-bottom: 0;
		font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
	}
	.ql-container {
		box-sizing: border-box;
		padding: 12px 15px;
		width: 100%;
		/* min-height: 30vh; */
		height: auto;
		background: #fff;
		font-size: 16px;
		line-height: 1.5;
		/* border: 1px #000 solid; */
	}
	.ql-active {
		color: #06c;
	}
	
	.save-button {
		position: fixed;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;
		width: 55px;
		height: 55px;
		background-color: #3c3e49;
		border-radius: 45px;
		z-index: 11;
		background-color: #02C069;
		right: 15px;
		bottom: 30px;
	}
	.save-button::before {
		position: absolute;
		content: "\2714";
		color: #fff;
		font-size: 60rpx;
	}
	
	.edit-button{
		position: fixed;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;
		width: 55px;
		height: 55px;
		background-color: #3c3e49;
		border-radius: 45px;
		z-index: 11;
		background-color: #02C069;
		right: 15px;
		bottom: 30px;
	}
	.edit-button::before {
		position: absolute;
		content: "\2710";
		color: #fff;
		font-size: 60rpx;
	}
</style>